<?php

declare(strict_types=1);

namespace app\validate\api\admin;

use app\validate\api\ApiBaseValidate;
use app\model\api\admin\Admin;
use app\common\constant\CacheKey;

class LoginValidate extends ApiBaseValidate
{
    protected $ex_data = [
        'old_jwt_data' => '',
    ];
    protected $rule = [
        'captcha_token' => 'require|length:32|alphaNum',

        'username|用户名' => 'require|max:64',
        'password|密码' => 'require|max:32',
        'captcha|验证码' => 'require|captcha',

        'refresh_token' => 'require|canRefresh',
    ];

    protected $message = [];

    protected $scene = [
        'loginBefore' => ['captcha_token'],
        'refreshToken' => ['refresh_token'],
    ];


    public function sceneLogin()
    {
        $check_rule = ['username', 'password', 'captcha'];

        $needLoginCapcha = config('zhtp.login_captcha_check');
        if ($needLoginCapcha == '0') {
            $check_rule = ['username', 'password'];
        } else if ($needLoginCapcha == '1') {
            $this->remove('captcha', 'captcha'); // 保留require+默认必有'placeholder';captcha切换为checkCaptcha
            $this->append('captcha', 'checkCaptcha');
        }

        $this->only($check_rule);

        return $this;
    }

    protected function checkCaptcha($value, $rule, $data = [])
    {
        $t_need = false;
        if (cache('_need_login_captcha_' . $data['username']) == '1') {
            $t_need = true;
        }
        if ($t_need) {
            if (!captcha_check($data['captcha'])) {
                return '图片验证码错误';
            }
        }
        return true;
    }


    protected function canRefresh($value, $rule, $data = [], $field = '', $title = '')
    {
        // 验证刷新令牌是否已被撤销;以后可改DB方式更多管理
        if (cache(CacheKey::RefreshTokenAdmin . md5($data['refresh_token'])) != '1') {
            return 'refreshToken已作废';
        }

        // 验证refreshToken是否有效+过期
        $admin_auth = \app\library\api\admin\Auth::instance();
        $re_jwt = $admin_auth->decodeJWT($data['refresh_token']);
        if ($re_jwt['code'] != 200) {
            return $re_jwt['msg'];
        }

        $old_jwt_data = $re_jwt['data'];
        $this->ex_data['old_jwt_data'] = $old_jwt_data;

        // 验证ip是否匹配等
        if (config('zhtp.loginip_check')) {
            if ($old_jwt_data['data']['login_ip'] != request()->ip()) {
                return '登录ip不匹配';
            }
        }

        // 验证账户是否存在+是否禁用
        $user = Admin::where(['id' => $old_jwt_data['data']['id']])->find();
        if (!$user) {
            return '账户不存在';
        }
        if ($user['status'] == Admin::STATUS_DISABLE) {
            return '账户已禁用';
        }


        return true;
    }
}
